﻿using System;
using System.Data;
using System.IO;
using System.Net;
using System.Text;
using System.Web;
using System.Xml;

namespace Nut.utils
{
    /// <summary>
    /// 保存常用的http 等方式的数据交互
    /// </summary>
    class NetUtil
    {
        /// <summary>
        /// POST提交XML文件获取返回数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <param name="strPost">XML数据</param>
        /// <returns></returns>
        private string PostXml(string url, string strPost)
        {
            string result = "";

            StreamWriter myWriter = null;

            HttpWebRequest objRequest = (HttpWebRequest)WebRequest.Create(url);
            objRequest.Method = "POST";
            objRequest.ContentLength = strPost.Length;
            objRequest.ContentType = "text/xml";//提交xml 
            //objRequest.ContentType = "application/x-www-form-urlencoded";//提交表单
            try
            {
                myWriter = new StreamWriter(objRequest.GetRequestStream());
                myWriter.Write(strPost);
            }
            catch (Exception e)
            {
                return e.Message;
            }
            finally
            {
                myWriter.Close();
            }

            HttpWebResponse objResponse = (HttpWebResponse)objRequest.GetResponse();
            using (StreamReader sr = new StreamReader(objResponse.GetResponseStream()))
            {
                result = sr.ReadToEnd();
                sr.Close();
            }
            return result;
        }

        /// <summary>
        /// Post提交获取返回数据
        /// </summary>
        /// <param name="url">网址</param>
        /// <returns></returns>
        public string GetWebContent(string url)
        {
            Stream outstream = null;
            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            // 要注意的这是这个编码方式，还有内容的Xml内容的编码方式
            Encoding encoding = Encoding.GetEncoding("UTF-8");
            byte[] data = encoding.GetBytes(url);

            // 准备请求,设置参数
            request = WebRequest.Create(url) as HttpWebRequest;
            request.Method = "POST";
            //request.ContentType = "text/plain";
            request.ContentLength = data.Length;

            outstream = request.GetRequestStream();
            outstream.Write(data, 0, data.Length);
            outstream.Flush();
            outstream.Close();
            //发送请求并获取相应回应数据

            response = request.GetResponse() as HttpWebResponse;
            //直到request.GetResponse()程序才开始向目标网页发送Post请求
            instream = response.GetResponseStream();
            sr = new StreamReader(instream, encoding);
            //返回结果网页(html)代码

            string content = sr.ReadToEnd();
            return content;
        }


        #region WebService返回的Xml转换成DataSet
        /// <summary>
        /// WebService返回的Xml转换成DataSet
        /// </summary>
        /// <param name="text">Xml字符</param>
        /// <returns></returns>
        private DataSet GetDataSet(string text)
        {
            try
            {
                XmlTextReader reader = new XmlTextReader(new StringReader(text));
                reader.WhitespaceHandling = WhitespaceHandling.None;
                DataSet ds = new DataSet();
                ds.ReadXml(reader);
                reader.Close();
                ds.Dispose();
                return ds;
            }
            catch
            {
                return null;
            }
        }
        #endregion
        #region 后台获取ashx返回的数据
        /// <summary>
        /// 后台获取ashx返回的数据
        /// </summary>
        /// <param name="relativePath">地址</param>
        /// <param name="data">参数</param>
        /// <returns></returns>
        public static string GetRequestJsonString(string relativePath, string data)
        {
            string requestUrl = GetRequestUrl(relativePath, data);

            try
            {
                WebRequest request = WebRequest.Create(requestUrl);
                request.Method = "GET";

                StreamReader jsonStream = new StreamReader(request.GetResponse().GetResponseStream());
                string jsonObject = jsonStream.ReadToEnd();

                return jsonObject;
            }
            catch
            {
                return string.Empty;
            }
        }

        public static string GetRequestUrl(string relativePath, string data)
        {
            
            string absolutePath = HttpContext.Current.Request.Url.AbsoluteUri;
            string hostNameAndPort = HttpContext.Current.Request.Url.Authority;
            string applicationDir = HttpContext.Current.Request.ApplicationPath;
            StringBuilder sbRequestUrl = new StringBuilder();
            sbRequestUrl.Append(absolutePath.Substring(0, absolutePath.IndexOf(hostNameAndPort)));
            sbRequestUrl.Append(hostNameAndPort);
            sbRequestUrl.Append(applicationDir);
            sbRequestUrl.Append(relativePath);
            if (!string.IsNullOrEmpty(data))
            {
                sbRequestUrl.Append("?");
                sbRequestUrl.Append(data);
            }
            return sbRequestUrl.ToString();
        }
        #endregion 

    }
}
